<?php

namespace App\Http\Controllers\Api\WenXin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Repository\Smilapp\SmilappNoticeRepository;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use App\Repository\AppUser\TouTiaoRepository;
use App\Repository\AppUser\TouTiaoUserOrderRepository;
use App\Http\Controllers\Api\BaseController;
/**
 * @OA\Tag(
 *     name="后台菜单模块",
 *     description="菜单模块",
 * )
 */
class AppWenXinSmailLoginController extends BaseController
{
  private $model;
  private $pname;
  private $log;
  public function __construct(TouTiaoRepository $TouTiaoRepository)
  {
    $this->model = $TouTiaoRepository;

    $this->pname = 'WenXinLogin';
    $this->log = new Logger('WenXinLogin');
    $this->log->pushHandler(
      (new RotatingFileHandler(storage_path('/logs/WenXinLogin.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
    );
  }
  // 获取登录信息  抖音小程序登录
  public function getSmailappUser(Request $request)
  {
    $params = $request->all();
    if (empty($params['shopId'])) {
      return $this->returnMsg(101, '未查询到店铺信息');
    }
    if (empty($params['appid'])) {
    }
    $shopId = $params['shopId'];
    // if (empty($shopId)) {
    //   return $this->returnMsg(101, '未查询到店铺信息');
    // }
    if (empty($params['code']) && empty($params['anonymousCode'])) {
      return $this->returnMsg(100, '请授权登录');
    }
    // $codes = !empty($params['anonymousCode']) ? $params['anonymousCode'] : $params['code'];
    // tt5a272c9ac518d44001 流量卡无限量宇轩  c4209c2dbc74d59ef3800c400091befde9cf9f7f secret参数
    // $getAppDouYin = DB::table('app_douyin_config')->where(['shop_id' => $params['shopId']])->first();
    $where = ['shop_id' => 5];
    if (!empty($params['appid'])) {
      $where = ['app_key' => $params['appid']];
    }
    // $getAppDouYin = [];
    $getAppDouYin = DB::table('app_douyin_config')->where($where)->first();
    // if (!$getAppDouYin) {
    //   return $this->returnMsg(101, '请联系商家');
    // }
    // if (empty($getAppDouYin->app_key) || empty($getAppDouYin->app_secret)) {
    //   return $this->returnMsg(102, '请联系商家配置参数');
    // }
    $data = [
      'appid' => !empty($getAppDouYin->app_key) ? $getAppDouYin->app_key : 'wxfc027f742ef44241',
      'secret' => !empty($getAppDouYin->app_secret) ? $getAppDouYin->app_secret : 'b53ee38f2783d9dc856e00823aa2556d',
      'code' => $params['code'],
      'grant_type' => 'authorization_code',
    ];
    $headers = [
      'Content-Type: application/json'
    ];
    $return = $this->getDouYinUid('', $data, $headers);
    // $return = [];
    // $this->log->info('参数' . json_encode($data) . '返回数据' . $return);
    // $return = '{"err_no":0,"err_tips":"success","data":{"session_key":"","openid":"","anonymous_openid":"VrBW4KrjY67LVJJ-","unionid":"","dopenid":""}}';
    $return = json_decode($return, true);
    // var_dump($return);
    // 将其存入数据库中
    if (isset($return['err_no']) && $return['err_no'] != 0) {
      return $this->returnMsg(109, '授权失败');
    }
    if (empty($return['data'])) {
      return $this->returnMsg(110, '授权失败');
    }
    $insertData = [
      'session_key' => $return['data']['session_key'],
      'openid' => $return['data']['openid'],
      'anonymous_openid' => $return['data']['anonymous_openid'],
      'unionid' => $return['data']['unionid'],
      'dopenid' => $return['data']['dopenid'],
      'shop_id' => $shopId,
    ];
    return $this->model->addOrEdit($insertData);
    return $this->returnMsg(200, '查询成功', $return);
  }
  // 存储用户
  public function getSmailappUserDetail(Request $request)
  {
    $params = $request->all();
    if (empty($params['user'])) {
      return $this->returnMsg(100, '请刷新页面');
    }
    $where = [
      'id' => $params['user'],
    ];
    return $this->model->edit($where, $params);
  }
  public function getDouYinUid($url, $data, $headers)
  {
    // 测试使用
    // $return = '{"err_no":0,"err_tips":"success","data":{"session_key":"","openid":"","anonymous_openid":"VrBW4KrjY67LVJJ-","unionid":"","dopenid":""}}';
    // return $return;
    if (empty($url)) {
      $url = 'https://api.weixin.qq.com/sns/jscode2session';
    }
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => json_encode($data),
      CURLOPT_HTTPHEADER => $headers,
    ));

    $response = curl_exec($curl);
    if ($error = curl_error($curl)) {
      var_dump($error);
    }
    curl_close($curl);
    $this->log->info('参数:' . json_encode($data) . '连接:' . $url . '返回结果' . $response);
    return $response;
  }
}
